//
//  FriendsListViewController.m
//  HJZWeiBo
//
//  Created by 蒋晨成 on 16/5/30.
//  Copyright © 2016年 蒋晨成. All rights reserved.
//

#import "FriendsListViewController.h"
#import "WeiboUser.h"
#import "UserListTableViewCell.h"
#import "MeDefaultViewController.h"
#import <MJRefresh.h>

@interface FriendsListViewController ()<UITableViewDelegate, UITableViewDataSource,  UserFollowDelegate>
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *cursor;
@property (nonatomic, assign) BOOL isRequest;
@end

@implementation FriendsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self.tableView registerClass:[UserListTableViewCell class] forCellReuseIdentifier:@"UserListTableViewCell"];
   
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if ([_cursor isEqualToString:@"0"] && _isRequest) {
            [self.tableView.mj_footer endRefreshing];
            return ;
        }
        if ([_userType isEqualToString:@"friend"]) {
            [self requestFriendListData];
        }else {
            [self requestFollowerListData];
        }
    }];
    
    
    self.cursor = @"0";
    self.dataSource = [NSMutableArray array];
    if ([_userType isEqualToString:@"friend"]) {
        [self requestFriendListData];
    }else {
        [self requestFollowerListData];
    }
    
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

- (void)requestFriendListData {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    NSLog(@"%@",accessToken);
   
    
    NSMutableDictionary* extraParaDict = [NSMutableDictionary dictionary];
    [extraParaDict setObject:_cursor forKey:@"cursor"];
    
//    [extraParaDict setObject:@"3" forKey:@"count"];
    
    [WBHttpRequest requestForFriendsListOfUser:_userID withAccessToken:accessToken andOtherProperties:extraParaDict queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        self.isRequest = YES;
        
        
        _cursor = [NSString stringWithFormat:@"%@",result[@"next_cursor"]];
        NSLog(@"%@",_cursor);
        NSLog(@"%@",result[@"total_number"]);
        NSArray *usersArray = result[@"users"];
        
        
        
        for (WeiboUser *user in usersArray) {
            [self.dataSource addObject:user];
           
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)requestFollowerListData{
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    
    NSMutableDictionary* extraParaDict = [NSMutableDictionary dictionary];
    
    [extraParaDict setObject:_cursor forKey:@"cursor"];
   
    [WBHttpRequest requestForFollowersListOfUser:_userID withAccessToken:accessToken andOtherProperties:extraParaDict queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
         self.isRequest = YES;
     
        
        _cursor = [NSString stringWithFormat:@"%@",result[@"next_cursor"]];
        
       
        NSArray *usersArray = result[@"users"];
        for (WeiboUser *user in usersArray) {
            [self.dataSource addObject:user];
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserListTableViewCell" forIndexPath:indexPath];
    cell.masterID = _userID;
    cell.userType = _userType;
    cell.user = _dataSource[indexPath.row];
    
    
    cell.delegate = self;
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([_userType isEqualToString:@"friend"]) {
        return @"全部关注";
    }else {
        return @"全部粉丝";
    }
    
}


- (void)followUserWithCell:(UITableViewCell *)cell isSelf:(BOOL)isSelf{
    UserListTableViewCell *listCell = (UserListTableViewCell *)cell;
    NSInteger index = [_tableView indexPathForCell:listCell].row;
    WeiboUser *user = _dataSource[index];
    
    if (!isSelf) {
        
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancenFollowAction = [UIAlertAction actionWithTitle:@"取消关注" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self cancelFollowUserWithAnotherUserID:user.userID];
        }];
        [alertVC addAction:cancenFollowAction];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancel];
        
        [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    }
    
    
}



- (void)cancelFollowUserWithAnotherUserID:(NSString *)anotherUserID {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    [WBHttpRequest requestForCancelFollowAUser:anotherUserID withAccessToken:accessToken andOtherProperties:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        
        NSLog(@"%@", result);
        
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MeDefaultViewController *meDefaultVC = [[MeDefaultViewController alloc] init];
    meDefaultVC.user = _dataSource[indexPath.row];
    [self.navigationController pushViewController:meDefaultVC animated:YES];
    
    
}


#pragma mark --- 分栏从左端开始 ---
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        if ([cell respondsToSelector:@selector(setSeparatorInset:)])
        {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)])
        {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
